﻿using CameraWin;
using CoreAudioApi;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml.Linq;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ABELGX
{
    /// <summary>
    /// WindowPG.xaml 的交互逻辑
    /// </summary>
    public partial class WindowPG : System.Windows.Window
    {
        DispatcherTimer timer;
        int timerCount = 0;
        Sensor battery = new Sensor(new SensorSet("", "%", 1, 0, "f0"));

        PageCommon pageCommon = new PageCommon();
        PageMotor pageMotor = new PageMotor();
        PageWater pageWater = new PageWater();
        PageCar pageCar = new PageCar();
        PageRule pageRule = new PageRule();

        WindowModel windowModel = new WindowModel();
        WindowBattery windowBattery = new WindowBattery();
        WindowMotor windowMotor = new WindowMotor();
        WindowSensorAir windowSensorAir = new WindowSensorAir();
        WindowSensorCommon windowSensorCommon = new WindowSensorCommon();
        WindowParameter windowParameter = new WindowParameter();

        List<System.Windows.Window> windows;
        public Car Car { get; }
        public WindowPG()
        {
            InitializeComponent();
            ImageLogo.Source = Config.GetLogo();
            Car = (App.Current as App).Work.Car;

            pageCommon.ParentWindow = this;
            pageMotor.SetCar(Car);
            pageWater.SetCar(Car);
            pageCar.SetCar(Car);
            pageRule.SetCar(Car);


            windowModel.SetCar(Car);
            windowBattery.SetCar(Car);
            windowMotor.SetCar(Car);
            windowSensorAir.SetCar(Car);
            windowSensorCommon.SetCar(Car);

            windows = new List<System.Windows.Window>
            {
                windowModel,
                windowBattery,
                windowMotor,
                windowSensorAir,
                windowSensorCommon,
                windowParameter
            };

            IconCarBattery.DataContext = Car.InfoMotor.Acc;
            IconBattery.DataContext = battery;
            IconWaterTemperature.DataContext = Car.InfoMotor.WaterTemperature;
            IconOilLevel.DataContext = Car.InfoMotor.OilLevel;
            IconMotor.DataContext = Car.InfoMotor.Rpm;

            Sensor1.DataContext = Car.InfoArm.Arm1;
            Sensor2.DataContext = Car.InfoArm.Arm2;
            Sensor3.DataContext = Car.InfoArm.Level;
            Sensor4.DataContext = Car.InfoArm.Length;
            Sensor5.DataContext = Car.InfoArm.Base;
            Sensor6.DataContext = Car.InfoArm.EndPitch;
            Sensor7.DataContext = Car.InfoArm.EndTurn;
            Sensor8.DataContext = Car.InfoArm.UnderX;
            Sensor9.DataContext = Car.InfoArm.UnderY;

            
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            PadLeft.SetInfo("大臂", Car.CmdArm.Arm1Up, Car.CmdArm.Arm1Down, null, null);

            Car.InitInfo();

            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(10000000);   //时间间隔.一秒=10000000
            timer.Tick += Timer_Tick;
            timer.Start();
            cameraInit();

            Point ptLeftUp = new Point(0, 0);
            Point ptRightDown = new Point(this.ActualWidth, this.ActualHeight);
            ptLeftUp = this.PointToScreen(ptLeftUp);
            ptRightDown = this.PointToScreen(ptRightDown);
            double Width = ptRightDown.X - ptLeftUp.X;
            double Height = ptRightDown.Y - ptLeftUp.Y;
            
            foreach (var window in windows)
            {

                setWindowLocation(window, ptLeftUp.X, ptLeftUp.Y + 80);
            }
            setWindowLocation(windowModel, ptLeftUp.X + 200, ptLeftUp.Y + 70);
        }

        void setWindowLocation(System.Windows.Window window,double left,double top)
        {
            window.WindowStartupLocation = WindowStartupLocation.Manual;
            window.Left = left;
            window.Top = top;
        }
        void showWindow(System.Windows.Window window)
        {
            foreach(var win in windows)
            {
                win.Hide();
                win.Topmost = false;
            }
            if (windows.Exists(x => x == window))
            {
                window.Show();
                //window.Activate();
                window.Topmost = true;
            }
        }

        
        private void Timer_Tick(object sender, EventArgs e)
        {
            timerCount++;
            try
            {
                if (timerCount % 5 == 1)
                {
                    ManagementClass mc = new ManagementClass("Win32_Battery");
                    ManagementObjectCollection moc = mc.GetInstances();
                    ManagementObjectCollection.ManagementObjectEnumerator mom = moc.GetEnumerator();
                    if (mom.MoveNext())
                    {
                        string bat = mom.Current.Properties["EstimatedChargeRemaining"].Value.ToString();
                        battery.Value = Convert.ToInt32(bat);
                    }
                }
                var sensor = Car.InfoSensor.Sensors[0];
                if(sensor.Status==0)
                {
                    sensor.Value = 10;
                    sensor.Status = 1;
                }
                else
                {
                    sensor.Value = 5;
                    sensor.Status = 0;
                }
            }
            catch { }
        }
        #region 摄像头
        List<Rect> camNormal;
        List<Rect> camExpand;
        List<UserControlVideo> camPanel;
        bool expand => PanelExpand.Visibility == Visibility.Visible;
        void cameraInit()
        {
            camNormal = new List<Rect>
            {
                new Rect(0,80,816,459),
                new Rect(0,539,272,153),
                new Rect(272,539,272,153),
                new Rect(544,539,272,153),
            };

            camExpand = new List<Rect>
            {
                new Rect(0,80,816,459),
                new Rect(320,582,208,117),
                new Rect(528,582,208,117),
                new Rect(736,582,208,117),
            };
            camPanel = new List<UserControlVideo>
            {
                CamPanel0,
                CamPanel1,
                CamPanel2,
                CamPanel3
            };
            for (int i = 0; i < Car.Cameras.Count; i++)
            {
                camPanel[i].Camera=Car.Cameras[i];
            }
            for (int i = Car.Cameras.Count; i < camPanel.Count; i++)
            {
                camPanel[i].Visibility = Visibility.Collapsed;
            }

            Task.Run(() => cameraWork());
        }
        void cameraWork()
        {
            int linkCount = 20;
            while (Car.Run)
            {
                Thread.Sleep(200);
                #region 摄像头连接
                try
                {
                    linkCount++;
                    if (linkCount >= 25)
                    {
                        linkCount = 0;
                        foreach (var cam in Car.Cameras)
                        {
                            try
                            {
                                var cam0 = Car.Cameras.Find(x => x != cam && x.Set.IP == cam.Set.IP && x.Set.Port == cam.Set.Port);
                                if (cam0 != null && cam0.UserID >= 0)
                                {
                                    cam.UserID = cam0.UserID;
                                }
                                else
                                {
                                    cam.Login();
                                    Thread.Sleep(100);
                                }

                                if (cam.UserID >= 0 && cam.RealHandle < 0)
                                {
                                    this.Dispatcher.Invoke(() =>
                                    {
                                        cam.RealPlay();
                                        Thread.Sleep(500);
                                        cam.StopPlay();
                                        Thread.Sleep(500);
                                        cam.RealPlay();
                                        Thread.Sleep(500);
                                        //cam.StartRecord(Config.VideoDayFolder);
                                    });
                                }
                            }
                            catch(Exception ex)
                            {
                                Config.WriteLog(ex.Message);
                            }
                        }
                    }
                }
                catch
                {

                }
                #endregion
            }
        }

        void cameraChange(ICamera cam)
        {
            try
            {
                List<ICamera> subs = Car.Cameras.FindAll(x => x != cam);
                cam.Main = true;
                camSetLoc(camPanel[cam.Index], expand ? camExpand[0] : camNormal[0]);

                for (int i = 0, j = 1; i < Car.Cameras.Count; i++)
                {
                    if (Car.Cameras[i] == cam)
                    {
                        continue;
                    }
                    Car.Cameras[i].Main = false;
                    camSetLoc(camPanel[Car.Cameras[i].Index], expand ? camExpand[j] : camNormal[j]);
                    j++;
                }
                cam.RefreshWindow();
            }
            catch
            {

            }
        }
        void camSetLoc(UserControlVideo panel,Rect loc)
        {
            panel.Width = loc.Width;
            panel.Height = loc.Height;
            Canvas.SetTop(panel, loc.Y);
            Canvas.SetLeft(panel, loc.X);
        }
        #endregion
        
        #region 功能菜单
        private void ButtonCar_Click(object sender, RoutedEventArgs e)
        {
            FrameFunc.Navigate(pageCar);
        }

        private void ButtonCommon_Click(object sender, RoutedEventArgs e)
        {
            FrameFunc.Navigate(pageCommon);
        }

        private void ButtonMotor_Click(object sender, RoutedEventArgs e)
        {

            FrameFunc.Navigate(pageMotor);
        }

        private void ButtonRule_Click(object sender, RoutedEventArgs e)
        {

            FrameFunc.Navigate(pageRule);
        }

        private void ButtonWater_Click(object sender, RoutedEventArgs e)
        {

            FrameFunc.Navigate(pageWater);
        }

        private void ButtonOther_Click(object sender, RoutedEventArgs e)
        {

        }
        #endregion

        #region 控制模式
        private void ControlModel_Click(object sender, RoutedEventArgs e)
        {
            //if (GridControlModel.Visibility == Visibility.Visible)
            //{
            //    GridControlModel.Visibility = Visibility.Collapsed;
            //}
            //else
            //{
            //    GridControlModel.Visibility = Visibility.Visible;
            //}

            showWindow(windowModel);
        }

        
        #endregion

        public void ShowPage(PageViewType viewType)
        {
            switch (viewType)
            {
                case PageViewType.Battery:
                    showWindow(windowBattery);
                    break;
                case PageViewType.SensorAir:
                    showWindow(windowSensorAir);
                    break;
                case PageViewType.SensorCommon:
                    showWindow(windowSensorCommon);
                    break;
                case PageViewType.MotorInfo:
                    showWindow(windowMotor);
                    break;
                case PageViewType.Parameter:
                    windowParameter.SetInfo(Config.Parameter.UserParameters, Config.UserSet);
                    showWindow(windowParameter);
                    break;
                default:
                    showWindow(null);
                    break;
            }
        }

        public void BringToFront(UIElement element)
        {
            if (element == null) return;

            var maxZ = MainPanel.Children.OfType<UIElement>()
              .Where(x => x != element)
              .Select(x => Canvas.GetZIndex(x))
              .Max();
            element.Visibility = Visibility.Visible;
            Canvas.SetZIndex(element, maxZ + 1);
        }

        public void BringToBack(UIElement element)
        {
            if (element == null) return;
            Canvas.SetZIndex(element, 0);
        }

        #region 底部面板
        private void PanelShow(bool expand)
        {
            if(expand)
            {
                PanelNormal.Visibility = Visibility.Collapsed;
                PanelExpand.Visibility = Visibility.Visible;
                
            }
            else
            {
                PanelExpand.Visibility = Visibility.Collapsed;
                PanelNormal.Visibility = Visibility.Visible;
            }
            cameraChange(Car.Cameras.Find(x => x.Main));
        }

        private void PanelDown_MouseUp(object sender, MouseButtonEventArgs e)
        {
            PanelShow(false);
        }

        private void PanelDown_TouchUp(object sender, TouchEventArgs e)
        {
            PanelShow(false);
        }

        private void PanelUp_MouseUp(object sender, MouseButtonEventArgs e)
        {
            PanelShow(true);
        }

        private void PanelUp_TouchUp(object sender, TouchEventArgs e)
        {
            PanelShow(true);
        }

        #endregion

        private void CloseWindow_MouseUp(object sender, MouseButtonEventArgs e)
        {
            timer.Stop();
            foreach (var win in windows)
            {
                win.Close();
            }
            Close();
        }

        private void IconLock_Click(object sender, EventArgs e)
        {

        }
    }
}
